package com.yunao.commons.metasearch.cookie;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.yunao.commons.enums.SearchTypeEnum;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CookieUtils {
    static Cache<String, Map<String, String>> cache = CacheBuilder.newBuilder()
            .maximumSize(100).expireAfterWrite(1, TimeUnit.DAYS).build();

    public static Map<String, String> get(final String type, final String u,
                                          final String p) {
        String key = DigestUtils.md5Hex(type + u);

        try {
            return cache.get(key, new Callable<Map<String, String>>() {

                public Map<String, String> call() throws Exception {
                    Map<String, String> result = new HashMap<String, String>();

                    if (type == SearchTypeEnum.MS_WEIBO_SINA.getSearchType())
                        result = new SinaCookie().load(u, p);
                    return result;
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
